var pricePlanId = null
var tableData1 = null, tableData2 = null;
var offsetH = (heightClient)*0.02;
initTableData1()
initTableData2()
var date = new Date()
var now = date.format("yyyy-MM-dd HH:mm:ss")
$(function () {
    layui.use(['table', 'form', 'laydate'], function () {
        var table = layui.table,
            form = layui.form,
            laydate = layui.laydate
        form.verify({
            planPrice: [/^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, '金额必须是正数']
        });
        var relevanceId = null;
        laydate.render({
            elem: '#effectiveTime',
            type: "datetime",
            min: now
        });
        var data = [
            {type: 'numbers', title: '序号', width: "3%"},
            {field: 'planName', title: '方案名称', width: "10%", sort: false, align: 'center'},
            {
                field: 'planType', title: '电价类型', sort: false, align: 'center', width: "10%", templet: function (d) {
                    if (d['planType'] == 0) return '<span class="layui-badge layui-bg-green">固定电价</span>'
                    else if (d['planType'] == 1) return '<span class="layui-badge ">阶梯电价</span>'
                    else return ''
                }
            },
            {
                field: 'planContent', title: '方案内容', sort: false, templet: function (d) {
                    var type = d['planType'];
                    if (type == 0) {
                        return "电价金额(元) : " + d.planPrice
                    } else if (type == 1) {
                        var peakValleyIs = d['peakValleyIs']
                        var period = '';
                        if (d.planLadderPeriod == 0) period = '月'
                        else if (d.planLadderPeriod == 1) period = '年'
                        var ladderSchemes = d.ladderSchemes;
                        var html = '';
                        html += '<p>阶梯<span style="margin-left: 130px"></span>金额(元)<span style="margin-left: 140px"></span>周期 : ' + period + '</p>'
                        for (var i = 0; i < ladderSchemes.length; i++) {
                            var ladderScheme = ladderSchemes[i];
                            html += "<p>";
                            html += ladderScheme.ladderName;
                            html += " (";
                            html += ladderScheme.ladderStartValue;
                            html += (!isEmpty(ladderScheme.ladderStartValue) && isEmpty(ladderScheme.ladderEndValue) ? '千瓦时以上' : " ~ " + ladderScheme.ladderEndValue + '千瓦时');
                            html += ") ";
                            if (peakValleyIs == 1) {
                                html += ' 尖值: ';
                                html += ladderScheme.cuspPrice;
                                html += ' 峰值: ';
                                html += ladderScheme.peakPrice;
                                html += ' 平值: ';
                                html += ladderScheme.flatPrice;
                                html += ' 谷值: ';
                                html += ladderScheme.valleyPrice;
                            } else if (peakValleyIs == 0) {
                                html += ' 标准值: ';
                                html += ladderScheme.standardPrice;
                            }
                            html += "</p>";
                        }
                        return html;
                    }
                }
            },
            {field: 'createTime', title: '创建时间', width: '10%', sort: false, align: 'center'},
            {field: 'validTime', title: '使用时间', width: '10%', sort: false, align: 'center'},
            {
                field: 'planStatus', title: '状态', sort: false, align: 'center', width: "8%", templet: function (d) {
                    if (d['planStatus'] == 1) return '<span class="font-green">使用中</span>'
                    else return ''
                }
            },
            {
                field: 'editStatus', title: '调价状态', sort: false, align: 'center', width: "8%", templet: function (d) {
                    if (d['editStatus'] == 1) return '<span class="layui-badge layui-bg-cyan">调价未生效</span>'
                    else if (d['editStatus'] == 0) return '<span class="layui-badge layui-bg-blue">未调价</span>'
                    else return ''
                }
            },
            {title: '操作', sort: false, align: 'center', width: "15%", toolbar: '#barDemo'}
        ];
        table.render(renderTable("#elePlanList", 'electricityPricePlan/page', data));
        table.on('tool(elePlanList)', function (obj) {
            var data = obj.data;
            pricePlanId = data.pricePlanId
            relevanceId = data.relevanceId
            if (obj.event == "editName") {
                layer.open({
                    type: 1,
                    title: "编辑名称",
                    offset: ['150px'],
                    btn: ["确认", "取消"],
                    btnAlign: "c",
                    area: ['400px', '200px'],
                    content: $("#planNameDiv"),
                    success: function () {
                        $("#planName-f").val(data.planName)
                    },
                    yes: function (i) {
                        var planName = $("#planName-f").val()
                        if (isEmpty(planName)) return layer.msg("请输入电价方案名称")
                        postAjaxReq("electricityPricePlan/edit/name", {
                            pricePlanId: pricePlanId,
                            planName: planName
                        }, function (res) {
                            layer.close(i);
                            if (res.code == 1) {
                                layer.closeAll();
                                table.reload('elePlanList');
                                layer.msg("保存成功")
                            } else {
                                layer.msg(res.msg)
                            }
                        })
                    },
                    end: function (i) {
                        pricePlanId = null
                        layer.close(i)
                        $("#planNameDiv").hide()
                        $("#planName-f").val('')
                    }
                })
            } else if (obj.event === "editPrice") {
                if (data['planType'] == 0) {
                    layer.open({
                        type: 1,
                        title: "电价方案",
                        offset: ['150px'],
                        area: ['400px', '300px'],
                        content: $("#elePlanDiv1"),
                        success: function () {
                            $("#planName1").attr("readonly", true)
                            form.val('editForm1', {
                                planName: data.planName,
                                planPrice: data.planPrice
                            })
                        },
                        end: function (i) {
                            $("#editForm1")[0].reset()
                            $("#elePlanDiv1").hide()
                            $("#planName1").attr("readonly", false)
                            layer.close(i)
                            pricePlanId = null
                        }
                    });
                } else if (data['planType'] == 1) {
                    layer.open({
                        type: 1,
                        title: "电价方案",
                        offset: [offsetH],
                        area: ['1100px', '500px'],
                        content: $("#elePlanDiv2"),
                        success: function () {
                            $("#planName2").attr("readonly", true)
                            form.val('editForm2', {
                                planName: data.planName,
                                planPrice: data.planPrice,
                                planLadderPeriod: data.planLadderPeriod,
                                peakValleyIs: data.peakValleyIs
                            })
                            if (data.peakValleyIs == 1) {
                                render1(data.ladderSchemes)
                            } else if (data.peakValleyIs == 0) {
                                render0(data.ladderSchemes)
                            }
                        },
                        end: function (i) {
                            $("#planName2").attr("readonly", false)
                            $("#editForm2")[0].reset()
                            $("#elePlanDiv2").hide()
                            layer.close(i)
                            pricePlanId = null
                        }
                    });
                }
            } else if (obj.event == 'history') {
                layer.open({
                    type: 1,
                    title: "历史记录信息",
                    offset: [offsetH],
                    area: ['600px', '400px'],
                    content: $("#historyDiv"),
                    success: function () {
                        getAjaxReq("electricityPricePlan/history/get", {relevanceId: data.relevanceId}, function (res) {
                            if (res.code) {
                                var list = res.data;
                                if (data['planType'] == 1) {
                                    list.forEach(function (e) {
                                        $("#historyAll").append('<div class="historyHeader" style="margin-top: 10px;position: relative"><h3 class="panel-heading">' +
                                            '<p><span class="text-green">电价方案:<span class="text">' +
                                            e.planName + '</span></span><span class="text-green">电价类型:<span class="layui-badge">阶梯电价</span></span></p><p><span class="text-green">使用时间:<span class="text">' +
                                            e.validTime + '</span></span><span class="iconfont pull-right icon-zhankai text-green stretched"></span></h3></div>')
                                        if (e.ladderSchemes) {
                                            if (e.peakValleyIs == 1) {
                                                var html = '<div class="historyContent" style="display: none"><table class="layui-table" style="margin-top: 0;"><thead><tr><th>阶梯电价</th><th>尖</th><th>峰</th><th>平</th> <th>谷</th></tr></thead><tbody>';
                                                e.ladderSchemes.forEach(function (e1) {
                                                    html = html + '<tr><td>' +
                                                        e1.ladderName + '&emsp;&emsp;&emsp;&emsp;' + e1.ladderStartValue + ' ~ ' + checkData(e1.ladderEndValue) + '</td><td>' +
                                                        e1.cuspPrice + '</td><td>' +
                                                        e1.peakPrice + '</td><td>' +
                                                        e1.flatPrice + '</td><td>' +
                                                        e1.valleyPrice + '</td></tr>';
                                                })
                                                html = html + '</tbody></table></div>';
                                                $("#historyAll").append(html)
                                            } else if (e.peakValleyIs == 0) {
                                                html = '<div class="historyContent" style="display: none"><table class="layui-table" style="margin-top: 0;"><thead><tr><th>阶梯电价</th><th>标准</th></tr></thead><tbody>';
                                                e.ladderSchemes.forEach(function (e1) {
                                                    html = html + '<tr><td>' +
                                                        e1.ladderName + '&emsp;&emsp;&emsp;&emsp;' + e1.ladderStartValue + ' ~ ' + checkData(e1.ladderEndValue) + '</td><td>' +
                                                        e1.standardPrice + '</td></tr>';
                                                })
                                                html = html + '</tbody></table></div>';
                                                $("#historyAll").append(html)
                                            }
                                            $(".stretched").click(function () {
                                                if ($(this).hasClass("icon-zhankai")) {
                                                    $(this).removeClass("icon-zhankai").addClass("icon-shouqi");
                                                    $(".historyContent").show()
                                                } else {
                                                    $(this).removeClass("icon-shouqi").addClass("icon-zhankai");
                                                    $(".historyContent").hide()
                                                }
                                            })
                                        }
                                    })
                                } else if (data['planType'] == 0) {
                                    list.forEach(function (e) {
                                        var html = '<div class="historyHeader" style="margin-top: 10px;position: relative"><h3 class="panel-heading">' +
                                            '<p><span class="text-green">电价方案:<span class="text">' +
                                            e.planName + '</span></span><span class="text-green">电价类型:<span class="layui-badge layui-bg-green">阶梯电价</span></span></p><p><span class="text-green">使用时间:<span class="text">' +
                                            e.validTime + '</span></span><span class="text-green">金额:<span class="red">' +
                                            e.planPrice + '￥</span></span></h3></div>';
                                        $("#historyAll").append(html)
                                    })
                                }
                            } else {
                                $("#historyAll").append('<p style="text-align: center">没找到历史记录!</p>');
                            }
                        })
                    },
                    end: function (i) {
                        $("#historyDiv").hide()
                        $("#historyAll").empty()
                        layer.close(i)
                    }
                });
            } else if (obj.event == 'future') {
                if (data['planType'] == 0) {
                    layer.open({
                        type: 1,
                        title: "新电价方案",
                        offset: ['150px'],
                        area: ['500px', '250px'],
                        content: $("#elePlanDiv4"),
                        success: function () {
                            getAjaxReq("electricityPricePlan/future/get",
                                {relevanceId: data.relevanceId},
                                function (res) {
                                    if (res.code) {
                                        form.val('editForm4', {
                                            planName: res.data.planName,
                                            planPrice: res.data.planPrice
                                        })
                                    }
                                })
                        },
                        end: function (i) {
                            $("#editForm4")[0].reset()
                            $("#elePlanDiv4").hide()
                            layer.close(i)
                            pricePlanId = null
                        }
                    });
                } else if (data['planType'] == 1) {
                    layer.open({
                        type: 1,
                        title: "新电价方案",
                        offset: [offsetH],
                        area: ['1100px', '400px'],
                        content: $("#elePlanDiv3"),
                        success: function () {
                            getAjaxReq("electricityPricePlan/future/get",
                                {relevanceId: relevanceId},
                                function (res) {
                                    if (res.code) {
                                        var d = res.data
                                        form.val('editForm3', {
                                            planName: d.planName,
                                            planLadderPeriod: d.planLadderPeriod,
                                            peakValleyIs: d.peakValleyIs
                                        })
                                        if (d.peakValleyIs == 1) {
                                            render11(d.ladderSchemes, '#projectList1')
                                        } else if (d.peakValleyIs == 0) {
                                            render00(d.ladderSchemes, '#projectList1')
                                        }
                                    }
                                })

                        },
                        end: function (i) {
                            $("#editForm3")[0].reset()
                            $("#elePlanDiv3").hide()
                            layer.close(i)
                            pricePlanId = null
                            relevanceId = null
                        }
                    })
                }
            } else if (obj.event == 'remove') {
                confirm("确定要删除吗?一旦删除不可恢复!", function () {
                    postAjaxReq("electricityPricePlan/remove",
                        {pricePlanId: pricePlanId},
                        function (res) {
                            if (res.code == 1) {
                                layer.msg("操作成功");
                                table.reload('elePlanList');
                            } else {
                                layer.msg(res.msg);
                            }
                            pricePlanId = null;
                            relevanceId = null;
                        })
                })
            }
        });
        form.on('submit(editSubmit1)', function (obj) {
            var url = null;
            var data = obj.field
            if (!isEmpty(pricePlanId)) {
                data.pricePlanId = pricePlanId
                data.relevanceId = relevanceId
                url = "electricityPricePlan/edit/1"
                layer.open({
                    type: 1,
                    title: "生效时间",
                    offset: ['150px'],
                    btn: ["确认", "取消"],
                    btnAlign: "c",
                    area: ['400px', '300px'],
                    content: $("#effectiveTimeDiv"),
                    yes: function (i) {
                        var adjustName = $("#adjustName").val()
                        if (isEmpty(adjustName)) return layer.msg("请输入调价计划名称")
                        var adjustEffectiveTime = $("#adjustEffectiveTime").val()
                        data['adjustEffectiveTime'] = adjustEffectiveTime
                        data['adjustName'] = adjustName
                        postAjaxReq(url, data, function (res) {
                            layer.close(i);
                            if (res.code == 1) {
                                layer.closeAll();
                                table.reload('elePlanList');
                                layer.msg("保存成功")
                            } else {
                                layer.msg(res.msg)
                            }
                        })
                    },
                    end: function (i) {
                        layer.close(i)
                        $("#effectiveTimeDiv").hide()
                        $("#adjustName").val('')
                        $("#effectiveTime").val('')
                        relevanceId = null
                    }
                })
            } else {
                url = "electricityPricePlan/save/1"
                postAjaxReq(url, data, function (res) {
                    if (res.code == 1) {
                        layer.closeAll();
                        table.reload('elePlanList');
                        layer.msg("保存成功")
                    } else {
                        layer.msg(res.msg)
                    }
                })
            }
            pricePlanId = null
        });
        table.on('tool(projectList)', function (obj) {
            if (obj.event === "del") {
                confirm("确认要删除么?", function () {
                    var index = obj.tr.data("index")
                    if (index == 0) return layer.msg("至少有一个阶梯!", {icon: 0})
                    var oldData = table.cache["projectList"];
                    oldData.splice(index)
                    table.reload('projectList', {
                        data: oldData
                    });
                })
            }
        });
        /*  table.on('edit(projectList)', function(obj){
              var value = obj.value ,//得到修改后的值
                  data = obj.data, //得到所在行所有键值
                  field = obj.field; //得到字段
          });*/
        //点击加号按钮时，新添一行
        $("#addRow").click(function () {
            var oldData = table.cache["projectList"];
            var flag = false;
            oldData.forEach(function (e) {
                for (var key in e) {
                    if (key != 'ladderName') {
                        var ele = e[key]
                        if (!positive_number.test(ele.toString().trim())) {
                            flag = true
                            return
                        }
                    } else {
                        if (isEmpty(e[key])) {
                            flag = true
                            return
                        }
                    }
                }
            })
            if (flag) return layer.msg("参数不能为空!", {icon: 0})
            var preRow = oldData[oldData.length - 1]
            if (isEmpty(preRow['ladderEndValue'])) return layer.msg("参数不能为空!", {icon: 0})
            if ((Number)(preRow['ladderEndValue']) <= (Number)(preRow['ladderStartValue']))
                return layer.msg("阶梯结束值必须大于阶梯开始值", {icon: 0})
            var nextRow = {}
            for (var key in preRow) {
                if (key == 'ladderStartValue')
                    nextRow[key] = preRow['ladderEndValue']
                else if (key == 'LAY_TABLE_INDEX')
                    nextRow[key] = preRow[key] + 1
                else
                    nextRow[key] = ''
            }
            oldData.push(nextRow);
            table.reload('projectList', {
                data: oldData
            });
        });
        form.on('submit(editSubmit3)', function (obj) {
            repeal();
        })
        form.on('submit(editSubmit4)', function (obj) {
            repeal();
        })

        function repeal() {
            confirm("确认要撤销本次调价吗？", function () {
                getAjaxReq("electricityPricePlan/future/repeal", {relevanceId: relevanceId}, function (res) {
                    if (res.code) {
                        layer.closeAll();
                        layer.msg("操作成功");
                        table.reload('elePlanList');
                        relevanceId = null
                    } else {
                        layer.msg("操作失败");
                    }
                })
            })
        }

        form.on('select(peakValleyIs)', function (data) {
            var val = data.value;
            if (val == 0) {
                initTableData2()
                render0(tableData2)
            } else if (val == 1) {
                initTableData1()
                render1(tableData1)
            }
        })
        form.on('submit(editSubmit2)', function (obj) {
            var ladderSchemes = table.cache["projectList"];
            if (isEmpty(ladderSchemes) || ladderSchemes.length == 0) return layer.msg("请至少填写一个阶梯", {icon: 0})
            var flag = false;
            var size = ladderSchemes.length - 1
            ladderSchemes.forEach(function (e, i) {
                if (i == size) {
                    for (var key in e) {
                        var ele = e[key]
                        if (key == 'ladderName') {
                            if (isEmpty(ele)) {
                                flag = true
                                return
                            }
                        } else if (key == 'ladderEndValue') {
                            if (!isEmpty(ele)) {
                                flag = true
                                return
                            }
                        } else {
                            if (!positive_number.test(ele)) {
                                flag = true
                                return
                            }
                        }
                    }
                } else {
                    for (var key in e) {
                        var ele = e[key]
                        if (key == 'ladderName') {
                            if (isEmpty(ele)) {
                                flag = true
                                return
                            }
                        } else {
                            if (!positive_number.test(ele)) {
                                flag = true
                                return
                            }
                        }
                    }
                }
            })
            if (flag) return layer.msg("阶梯参数不合法!", {icon: 0})
            if (size > 0) {
                var flag2 = false
                ladderSchemes.forEach(function (e, i) {
                    if (i > 0) {
                        flag2 = (Number)(ladderSchemes[i]['ladderStartValue']) == (Number)(ladderSchemes[i - 1]['ladderEndValue'])
                        if (flag2) return
                    }
                })
                if (!flag2) return layer.msg("阶梯开始值和结束值必须连续!", {icon: 0})
            }

            var url = null;
            var data = obj.field
            var json = {
                pricePlan: data,
                ladderSchemes: ladderSchemes
            }
            if (!isEmpty(pricePlanId)) {
                data.pricePlanId = pricePlanId
                data.relevanceId = relevanceId
                url = "electricityPricePlan/edit/2"
                layer.open({
                    type: 1,
                    title: "生效时间",
                    offset: ['150px'],
                    btn: ["确认", "取消"],
                    btnAlign: "c",
                    area: ['400px', '400px'],
                    content: $("#effectiveTimeDiv"),
                    yes: function (i) {
                        var adjustName = $("#adjustName").val()
                        if (isEmpty(adjustName)) return layer.msg("请输入调价计划名称")
                        var adjustEffectiveTime = $("#effectiveTime").val()
                        json['adjustEffectiveTime'] = adjustEffectiveTime
                        json['adjustName'] = adjustName
                        save(url, json, i)
                    },
                    end: function (i) {
                        layer.close(i)
                        $("#effectiveTimeDiv").hide()
                        $("#adjustName").val('')
                        $("#effectiveTime").val('')
                        relevanceId = null
                    }
                })
            } else {
                url = "electricityPricePlan/save/2"
                save(url, json)
            }
        });

        $("#search").click(function () {
            var planName = $("#planName").val(),
                planStatus = $("#planStatus").val();
            if (planStatus == -1) planStatus = null
            table.reload('elePlanList', {
                page: {curr: 1},
                where: {
                    planName: planName,
                    planStatus: planStatus
                }
            })
        });
        $("#addElePlan2").click(function () {
            layer.open({
                type: 1,
                title: "新增电价方案",
                offset: [offsetH],
                area: ['1100px', '500px'],
                content: $("#elePlanDiv2"),
                success: function () {
                    initTableData1()
                    initTableData2()
                    render1(tableData1)
                },
                end: function (i) {
                    layer.close(i)
                    $("#editFormDiv2").hide()
                    $("#editForm2")[0].reset()
                    $("#planName2").attr("readonly", false)
                    $("#elePlanDiv2").hide();
                }
            });
        })

        function render1(data) {
            table.render({
                elem: '#projectList',
                data: data,
                page: false,
                width: 920,
                cols: [[
                    {field: 'ladderName', title: '阶梯名称', edit: 'text', sort: false, align: 'center'},
                    {field: 'ladderStartValue', title: '阶梯开始值', edit: 'text', sort: false, align: 'center'},
                    {field: 'ladderEndValue', title: '阶梯结束值', edit: 'text', sort: false, align: 'center'},
                    {field: 'cuspPrice', title: '尖', edit: 'text', sort: false, align: 'center'},
                    {field: 'peakPrice', title: '峰', edit: 'text', sort: false, align: 'center'},
                    {field: 'flatPrice', title: '平', edit: 'text', sort: false, align: 'center'},
                    {field: 'valleyPrice', title: '谷', edit: 'text', sort: false, align: 'center'},
                    {title: '操作', sort: false, align: 'center', edit: 'text', toolbar: '#barDemo2'}
                ]]
            });
        }

        function render0(data) {
            table.render({
                elem: '#projectList',
                data: data,
                page: false,
                width: 920,
                cols: [[
                    {field: 'ladderName', title: '阶梯名称', edit: 'text', sort: false, align: 'center'},
                    {field: 'ladderStartValue', title: '阶梯开始值', edit: 'text', sort: false, align: 'center'},
                    {field: 'ladderEndValue', title: '阶梯结束值', edit: 'text', sort: false, align: 'center'},
                    {field: 'standardPrice', title: '标准', edit: 'text', sort: false, align: 'center'},
                    {title: '操作', sort: false, align: 'center', edit: 'text', toolbar: '#barDemo2'}
                ]]
            });
        }

        function save(url, data, i) {
            jsonAjaxReq(url, data, function (res) {
                layer.close(i);
                if (res.code == 1) {
                    layer.closeAll();
                    table.reload('elePlanList');
                    layer.msg("保存成功")
                } else {
                    layer.msg(res.msg)
                }
            })
        }

        function render00(data, ele) {
            table.render({
                elem: ele,
                data: data,
                page: false,
                width: 920,
                cols: [[
                    {field: 'ladderName', title: '阶梯名称', sort: false, align: 'center'},
                    {field: 'ladderStartValue', title: '阶梯开始值', sort: false, align: 'center'},
                    {field: 'ladderEndValue', title: '阶梯结束值', sort: false, align: 'center'},
                    {field: 'standardPrice', title: '标准', sort: false, align: 'center'}
                ]]
            });
        }

        function render11(data, ele) {
            table.render({
                elem: ele,
                data: data,
                page: false,
                width: 920,
                cols: [[
                    {field: 'ladderName', title: '阶梯名称', sort: false, align: 'center'},
                    {
                        field: 'ladderStartValue', title: '阶梯开始值', sort: false, align: 'center'
                    },
                    {field: 'ladderEndValue', title: '阶梯结束值', sort: false, align: 'center'},
                    {field: 'cuspPrice', title: '尖', sort: false, align: 'center'},
                    {field: 'peakPrice', title: '峰', sort: false, align: 'center'},
                    {field: 'flatPrice', title: '平', sort: false, align: 'center'},
                    {field: 'valleyPrice', title: '谷', sort: false, align: 'center'}
                ]]
            });
        }
    })
    ;
})
;

function checkData(data) {
    if (isEmpty(data)) return '最大'
    return data;
}

function initTableData1() {
    tableData1 = [{
        ladderName: '',
        ladderStartValue: 0,
        ladderEndValue: '',
        cuspPrice: '',
        peakPrice: '',
        flatPrice: '',
        valleyPrice: ''
    }]
}

function initTableData2() {
    tableData2 = [{
        ladderName: '',
        ladderStartValue: 0,
        ladderEndValue: '',
        standardPrice: ''
    }]
}